home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 4 / Info_Mac IV CD-ROM (Pacific HiTech Inc.)(August 1994).iso / Science / RLaB / examples / least_squares.r < prev    next >
Text File  |  1994-04-25  |  1KB  |  64 lines

  1. //-------------------------------------------------------------------//
  2. //
  3. //  A Simple Least Squares Data Fitting Example
  4. //
  5.  
  6. //
  7. //  Set the random number generator to uniform distribution, with
  8. //  lower bound = -2, and upper bound = 5.
  9. //
  10.  
  11.   rand("uniform",-2, 5);
  12.  
  13. //  Generate random data with a linearly varying component.  The
  14. //  linearly varying component is formed, and stored in `off'. The
  15. //  simulated, measured data is stored in `b'.
  16. //
  17.  
  18.   off = 0:-20:-.2;
  19.   b = ((off + 22) + rand( size(off) ));
  20.  
  21. //
  22. //  Generate the Data matrix, A.
  23. //
  24. //      | 1  t  t^2 |
  25. //  A = | 1  t  t^2 |
  26. //      | 1  t  t^2 |
  27. //        .  .   .
  28. //        .  .   .
  29. //        .  .   .
  30. //
  31.  
  32.   m = b.n;
  33.   t = (1:m)/m;
  34.  
  35.   A = [ ones(m,1), t', (t.^2)' ];
  36.  
  37. //
  38. //  Now use left division (least squares) to solve for `x'.
  39. //
  40.  
  41.   x = A\b';
  42.  
  43. //
  44. //  Create a simple function that uses the computed parameters to
  45. //  make predictions.
  46. //
  47.  
  48.   ls = function(t)
  49.   {
  50.     return x[1] + x[2]*t + x[3]*t.^2;
  51.   }
  52.  
  53. //
  54. //  Plot a comparison of the original data, and the computed
  55. //  values.
  56. //
  57.  
  58.   plgrid ();
  59.   ptitle ( "RLaB Least Squares Example" );
  60.   xlabel ( "Independent Variable" );
  61.   ylabel ( "Dependent Variable" );
  62.  
  63.   plot( [ t; b; ls( t ) ]' );
  64.